<template>
  <div class="page">
    <div class="top">
      <div class="flex_center">
        <div class="top_image flex_center">
          <img v-if="!isLogo" class="logo_image" src="@/assets/logo.png" />
          <img v-else class="logo_image" :src="baseLogo" />
        </div>
      </div>
      <div class="flex_center">
        <div class="price_left">￥</div>
        <div class="price_right">{{ userInfos.amount }}</div>
      </div>
      <div class="flex_center time_top">
        <div class="top_three_left">支付剩余时间</div>
        <div class="price_right flex_center">
          <div class="time_box flex_center">
            {{ pay_minute }}
          </div>
          <div class="dian flex_center">:</div>
          <div class="time_box flex_center">
            {{ pay_second }}
          </div>
        </div>
      </div>
      <div class="line-container">
        <div class="line"></div>
      </div>
      <div class="content_text_box">
        <div class="text_flex flex_between">
          <div>订单号</div>
          <div>{{ mer_ord_id }}</div>
        </div>
        <div class="text_flex flex_between">
          <div>收款方</div>
          <div>{{ userInfos.merName }}</div>
        </div>
        <div class="text_flex flex_between">
          <div>商品名称</div>
          <div>{{ userInfos.goodsInf }}</div>
        </div>
      </div>
    </div>
    <!-- 支付方式 -->
    <div class="payType_box">
      <div class="title">支付方式</div>
      <div class="">
        <div class="payType_first flex" v-for="(item, index) in modeList.value" :key="index"
          @click="handleCheckPayType(index, item.name)">
          <div class="pay_img_box flex_center">
            <img v-if="item.name == 'quick'" class="img" src="@/assets/pay_1.png" alt="快捷支付">
            <img v-if="item.name == 'ali'" class="img" src="@/assets/pay_3.png" alt="快捷支付">
            <img v-if="item.name == 'weChat'" class="img" src="@/assets/pay_2.png" alt="快捷支付">
            <img v-if="item.name == 'unionpay'" class="img" src="@/assets/pay_4.png" alt="快捷支付">
          </div>
          <div class="pay_text flex_center">{{ {
            'quick': '快捷支付', 'ali': '支付宝支付', 'EBank': '网银支付', 'unionpay': '银联支付',
            'weChat': '微信支付',
          }[item.name] }}</div>
          <div class="dui_box flex_center">
            <img v-if="index == activeOne" class="img" src="@/assets/check_dui.png" alt="">
            <img v-else class="img" src="@/assets/uncheck_dui.png" alt="">
          </div>
        </div>
      </div>
    </div>
    <div class="nbsp"></div>
  </div>
  <!-- 首页确认支付 点击展示下一步 -->
  <div class="submit_pay">
    <div class="flag_box">
      <van-button class="global_btn" type="danger" :disabled="isErrorFirst"
        @click="handleSubmitPay(1)">确认支付</van-button>
    </div>
  </div>
  <van-action-sheet class="action_sheet" v-model:show="isShow" :closeable="false">
    <div class="action_sheet_wrap">
      <div class="action_sheet_top flex_between">
        <div class="sheet_close" @click="handleClosePhone">取消</div>
        <div class="title">快捷支付</div>
        <div class="sheet_right sheet_close" style="opacity: 0;">取消</div>
      </div>
      <div class="action_sheet_content">
        <div class="phone_title">手机号</div>
        <input ref="phoneNumber" class="phone_value" type="text" placeholder="请输入手机号"
          @input="handleTestPhone($event.target.value)">
        <img v-if="isClosePhone" src="@/assets/Vector@2x.png" class="Vector2x" alt="" @click="handleClearPhone">
      </div>
      <van-button class="global_btn" type="danger" :disabled="isNextDisabled" @click="handlePhoneNext">下一步</van-button>
    </div>
  </van-action-sheet>
  <van-action-sheet class="action_sheet" v-model:show="isShowPay" :closeable="false">
    <div class="action_sheet_wrap">
      <div class="action_sheet_top flex_between">
        <div @click="handlePrev" style="text-align:left;display:flex;align-items:center;">
          <van-icon name="arrow-left" color="#333333" size="20px" />
        </div>
        <div class="title title_left">{{ bankList.value && bankList.value.length > 0 ? '选择付款银行卡' : '暂未绑卡，添加银行卡付款' }}
        </div>
        <div class="sheet_right sheet_close" style="opacity: 0;">取消</div>
      </div>
      <div class="scroll_box" v-if="bankList.value && bankList.value.length > 0"
        :style="bankList.value.length > 3 ? 'overflow-y:scroll' : ''">
        <div class="bank_box flex" v-for="(item, index) in bankList.value" :key="item"
          @click="handleChangeCard(index, item)">
          <div class="bank_box_icon_box">
            <!-- icon 精灵图标 -->
            <div class="img bank-img" :class="item.binBankId"></div>
          </div>
          <div class="bank_box_text">{{ item.binBankName }}{{ item.bankAccType == 0 ? '储蓄卡' : '信用卡' }}{{
            `(${item.bankAccountLast})` }}
          </div>
          <div class="bank_box_right_icon flex_center">
            <img v-if="index == activeTwo" class="img" src="@/assets/check_dui.png" alt="">
            <img v-else class="img" src="@/assets/uncheck_dui.png" alt="">
          </div>
        </div>
      </div>
      <!-- 添加银行卡  -->
      <div class="bank_box flex" @click="handleTargetBank">
        <div class="bank_box_icon_box">
          <img class="img" src="@/assets/add_bank_card.png" alt="">
        </div>
        <div class="bank_box_text">添加银行卡</div>
        <div class="bank_box_right_icon flex_center">
          <van-icon name="arrow" color="#cccccc" size="20px" />
          <!-- <img class="img" src="@/assets/uncheck_dui.png" alt=""> -->
        </div>
      </div>
      <!-- 有绑卡信息 直接确认支付 -->
      <div style="margin-top:30px">
        <van-button class="global_btn" type="danger" @click="handleSubmitPay(2)">确认支付</van-button>
      </div>
    </div>
  </van-action-sheet>

  <!-- 超时弹框 -->
  <van-dialog class="agreement_btn" v-model:show="isTimeOut" :show-confirm-button="false">
    <div class="flex_colum" style="justify-content:space-between;padding: 40px;">
      <div class="alert_agreement">订单已超时，请重新下单支付</div>
      <van-button class="global_btn" type="danger" @click="handleOutTimeTarget">确定</van-button>
    </div>
  </van-dialog>

  <!-- 确认支付弹框 -->
  <van-dialog class="agreement_btn" v-model:show="isConfirmPayment" :show-confirm-button="false">
    <div class="flex_colum" style="justify-content:space-between;padding: 40px;">
      <div class="alert_agreement">请确认是否完成支付？</div>
      <div style="display: flex;justify-content: space-between;width: 100%;">
        <van-button class="global_bt" @click="cancalPay">取消支付</van-button>
        <van-button class="global_btn" type="danger" @click="queryPay">支付完成</van-button>
      </div>
    </div>
  </van-dialog>

  <!-- 订单尚未完成支付，请尽快支付！ -->
  <van-dialog class="agreement_btn" v-model:show="isConfirmNextPayment" :show-confirm-button="false">
    <div class="flex_colum" style="justify-content:space-between;padding: 40px;">
      <div class="alert_agreement">订单尚未完成支付，请尽快支付！</div>
      <van-button class="global_btn" type="danger" @click="nextQueryPay">去支付</van-button>
    </div>
  </van-dialog>
</template>

<script setup>
import { paymentListH5, queryOrderExpireTime, quickPayment, agreementAndBankInfo, enableBankListH5, confirmH5, getLogoImage, getQueryAgreementId, SetParamTmp, weChatInit, getOrderStatus } from '@/api/api.js'
import { useRouter, useRoute } from 'vue-router'
import { reactive, ref, onMounted, getCurrentInstance, inject, watch } from 'vue'
import { useCounterStore } from '../../store/counter';

const counter = useCounterStore()
const { proxy } = getCurrentInstance()
// const mes = inject('$Toast')
const numTime = ref(0)
const isShow = ref(false)
const isErrorFirst = ref(false)
const isShowPay = ref(false)
const isNextDisabled = ref(true)
const isTimeOut = ref(false)
const isConfirmPayment = ref(false)
const isConfirmNextPayment = ref(false)
// const isLoading = ref(false)
const orderTimer = ref(null)
const router = useRouter()
const activeOne = ref(0)
const activeName = ref('')
const activeTwo = ref(null)
const parsedParameters = reactive({})
const modeList = reactive([])
const userInfos = reactive({})
const mer_ord_id = ref('')
const effectTime = ref('')
// 时间分钟
const pay_minute = ref('00')
const pay_second = ref('00')
// 定时查询状态
const payInterval = ref(null)
const queryStatus = ref(null)

const bankList = reactive([])
// logo 图片
const baseLogo = ref('')
const isLogo = ref(true)
const coverImgLogo = ref('')
// 支持的银行列表
// 借记卡数据
const chuListData = reactive([])
// 储蓄卡数据
const depListData = reactive([])
const isClosePhone = ref(false)

// 浏览器环境
const isWeChatBrowser = ref(false) // 是否是微信浏览器
const isAliBrowser = ref(false) // 是否是支付宝浏览器
const isNativeBrowser = ref(false) //普通浏览器环境

onMounted(() => {
  getUrl()
})
// window.sessionStorage
// console.log("🚀 ~ window.sessionStorage:", window)

// 订单超时跳转 超时页面
const handleOutTimeTarget = () => {
  isTimeOut.value = false
  router.push({
    path: '/orderTimeout',
    query: {
      payType: 'timeout'
    }
  })
}
const getPaymentList = () => {
  // 初始化订单信息数据

  userInfos.value = proxy.$globalFn.getStorage('urlParameters')
  mer_ord_id.value = userInfos.value.orderId;
  userInfos.merName = userInfos.value.merName
  userInfos.goodsInf = userInfos.value.goodsInf
  userInfos.amount = proxy.$globalFn.convertCent2Dollar(userInfos.value.amount)

  parsedParameters.value = parsedParameters.value ? parsedParameters.value : {};
  window.console.log('parsedParameters.value', parsedParameters.value)
  paymentListH5(parsedParameters.value).then(res => {
    if (res.retCode == "0000") {
      isErrorFirst.value = false
      getOrderTime(); // 获取订单有效期时间
      proxy.$globalFn.setStorage("orderSign", res.data.orderSign);
      proxy.$globalFn.setStorage("urlSourceSign", res.data.sourceSign);
      let mapList = res.data.modeList || []
      mapList.length > 1 && mapList.sort((a, b) => a.weight - b.weight)
      modeList.value = mapList

      if (modeList.value.length) {
        activeName.value = modeList.value[0].name

        // 处理环境浏览器过滤掉不同支付方式
        if (isWeChatBrowser.value) {
          // 微信浏览器 过滤掉  ‘支付宝’ ‘网银’ 支付
          const filtereWechatdData = modeList.value.filter(item => item.name !== 'ali' && item.name !== 'unionpay');
          modeList.value = filtereWechatdData;

        } else if (isAliBrowser.value) {
          // 支付宝浏览器 过滤掉  ‘微信’ ‘网银’ 支付
          const filtereAlidData = modeList.value.filter(item => item.name !== 'weChat' && item.name !== 'unionpay');
          modeList.value = filtereAlidData;
        }
      } else {
        proxy.$showToast("没有获取到支付方式,请重新下单！");
        return
      }

      // 处理渲染
      if (modeList.value.length && modeList.value.length == 1) {
        // {
        //   'quick': '快捷支付', 'ali': '支付宝支付', 'unionpay': '银联支付',
        //     'weChat': '微信支付',
        // }

        if (modeList.value[0].name == 'quick') {
          kuaigetPayInit();
        } else if (modeList.value[0].name == 'weChat') {
          console.log('微信')
          weChatGetInit(29)
          // window.location.href = parsedParameters.value.微信
          // window.location.href = 'weixin://dl/business/?t=your_miniapp_appid';
        } else if (modeList.value[0].name == 'ali') {
          console.log('支付宝')
          weChatGetInit(30)
        } else if (modeList.value[0].name == 'unionpay') {
          console.log('网银')
        }
      }

    } else {
      isErrorFirst.value = true
      proxy.$showToast(res.retMsg);
    }
  }).catch((err) => {
    proxy.$showToast(err);
  })
}

// 判断浏览器环境
const checkWeChatBrowser = () => {
  const userAgent = navigator.userAgent.toLowerCase();
  console.log('userAgent======>', userAgent)
  if (userAgent.includes('micromessenger')) {
    isWeChatBrowser.value = true;
    console.log('微信环境')
  } else if (userAgent.includes('alipay')) {
    isAliBrowser.value = true;
    console.log('支付宝环境')
  } else {
    isNativeBrowser.value = true;
    console.log('普通原生环境')
  }
}

// 去支付
const nextQueryPay = () => {
  handleSubmitPay(1)
  isConfirmNextPayment.value = false
}

// 防抖
function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// 确认支付
const queryPay = debounce(() => {
  getPayValidity()
}, 1000)

const getPayValidity = async () => {
  try {
    let res = await queryOrderExpireTime(userInfos.value)
    if (res.retCode == "0000") {
      effectTime.value = res.data;
      startCountDown(); // 开始倒计时

      // 再查询订单状态
      getPayData()
    } else {
      // 订单超时提示
      getOutPayData()
    }
  } catch (error) {
    console.error(error);
    proxy.$showToast("获取订单有效期时间接口错误，请重新尝试！")
  }
}

// 确认支付订单超时状态
async function getOutPayData() {
  var lunQuery = proxy.$globalFn.getStorage('urlParameters')
  lunQuery.orderSign = proxy.$globalFn.getStorage('orderSign')
  let res = await getOrderStatus(lunQuery)
  try {
    if (res.retCode == "0000") {
      router.push({
        path: '/success',
        query: {
          payType: "kuaijie"
        }
      })
    } else {
      router.push({
        path: '/orderTimeout',
        query: {
          payType: 'timeout'
        }
      })
    }
  } catch (err) {
    router.push({
      path: '/fail'
    });
  }
}

// 确认支付订单状态
async function getPayData() {
  var lunQuery = proxy.$globalFn.getStorage('urlParameters')
  lunQuery.orderSign = proxy.$globalFn.getStorage('orderSign')
  let res = await getOrderStatus(lunQuery)
  try {
    if (res.retCode == "0000") {
      router.push({
        path: '/success',
        query: {
          payType: "kuaijie"
        }
      })
    } else {
      isConfirmNextPayment.value = true
    }
  } catch (err) {
    router.push({
      path: '/fail'
    });
  }
}

// 取消支付
const cancalPay = debounce(() => {
  getValidity()
}, 1000)

// 先查询支付有效期内 再查支付状态
const getValidity = async () => {
  try {
    let res = await queryOrderExpireTime(userInfos.value)
    if (res.retCode == "0000") {
      effectTime.value = res.data;
      startCountDown(); // 开始倒计时

      // 再查询订单状态
      getData()
    } else {
      // 订单超时提示
      isTimeOut.value = true;
    }
  } catch (error) {
    console.error(error);
    proxy.$showToast("获取订单有效期时间接口错误，请重新尝试！")
  }
}

// 订单状态
async function getData() {
  var lunQuery = proxy.$globalFn.getStorage('urlParameters')
  lunQuery.orderSign = proxy.$globalFn.getStorage('orderSign')
  let res = await getOrderStatus(lunQuery)
  try {
    if (res.retCode == "0000") {
      router.push({
        path: '/success',
        query: {
          payType: ""
        }
      })
    } else {
      isConfirmPayment.value = false
    }
  } catch (err) {
    router.push({
      path: '/fail'
    });
  }
}

const getUrl = () => {
  // 判断浏览器环境
  checkWeChatBrowser()
  // 获取地址栏中的参数
  if (window.location.search != "") {
    var currentUrl = window.location.search;
  } else {
    var currentUrl = window.location.hash;
  }
  console.log('currentUrl', currentUrl)
  proxy.$globalFn.setStorage('infoParams', currentUrl)
  // 判断是否存在参数
  // 正确的参数格式
  if (/(?:\?)(.+)/.test(currentUrl)) {

    var urlParameters = proxy.$globalFn.getUrlParameters(currentUrl);
    // console.log("urlParameters", urlParameters.quick_sign_type)
    var regex = /\+/g; // 定义正则表达式，匹配所有的 "+" 符号
    var newDateString = urlParameters.expireTime.replace(regex, " "); // 使用 replace 方法替换字符串中所有匹配的文本
    urlParameters.expireTime = newDateString;
    // urlParameters.quickSignType = 'quick-web';
    // urlParameters.gateId = 'SBC';
    // delete urlParameters.gateId
    // delete urlParameters.quickSignType
    proxy.$globalFn.setStorage('urlParameters', urlParameters)
    parsedParameters.value = proxy.$globalFn.getStorage('urlParameters')
    proxy.$globalFn.setStorage('phone', parsedParameters.value.mobileId || '')
    handleGetLogo()
    getPaymentList();
    // 获取支付方式类型  走网关
    if (parsedParameters.value && parsedParameters.value.quick_sign_type && parsedParameters.value.quick_sign_type == 'quick-web') {
      //  判断是否是首次进入还是 网关过来的  ‘isPaySeq’
      let isPaySeq = proxy.$globalFn.getStorage('paySeq') || ''
      if (isPaySeq) {
        let pro = {
          merId: parsedParameters.value.merId,
          merDate: parsedParameters.value.orderDate,
          orderId: parsedParameters.value.orderId,
          paySeq: isPaySeq
        }
        function getOtime() {

          getQueryAgreementId(pro).then((res) => {
            console.log('pro', pro)
            if (res.retCode == '0000') {
              // 接下来执行步骤  先写死
              // res.data.usrPayAgreementId = '124324';
              if (res.data.status == 1) {
                if (res.data.mobileId && res.data.usrPayAgreementId) {
                  proxy.$globalFn.setStorage('phone', res.data.mobileId)
                  agreementAndBankInfo({
                    mobileId: res.data.mobileId,
                    agreementId: res.data.usrPayAgreementId
                  }).then(res => {

                    window.console.log(res.retCode)
                    window.console.log(res.retMsg)
                    if (res.retCode == "0000") {
                      if (
                        res.data.bankAndAgreementInfoList &&
                        res.data.bankAndAgreementInfoList.length
                      ) {
                        if (!proxy.$globalFn.getStorage('isFlag')) {
                          proxy.$globalFn.setStorage('isFlag', true)
                          setTimeout(() => {
                            proxy.$showToast('绑卡成功！')
                          }, 1000);
                        }
                        // 查询的协议信息 有数据就跳转页面到 银行列表页
                        proxy.$globalFn.setStorage(
                          "userBankAndAgreementInfoList",
                          res.data.bankAndAgreementInfoList
                        );

                        bankList.value = proxy.$globalFn.getStorage('userBankAndAgreementInfoList') || []
                        if (parsedParameters.value && parsedParameters.value.quick_sign_type && parsedParameters.value.quick_sign_type == 'quick-web') {
                          bankList.value.length > 1 && // 假设 bankList.value 是一个包含对象的数组
                            bankList.value.sort((a, b) => {
                              // 如果 a 的 chooseFlag 为 '1' 而 b 的 chooseFlag 不为 '1'，将 a 移动到前面
                              if (a.chooseFlag == '1' && b.chooseFlag != '1') {
                                return -1;
                              }
                              // 如果 a 的 chooseFlag 不为 '1' 而 b 的 chooseFlag 为 '1'，将 b 移动到前面
                              if (a.chooseFlag != '1' && b.chooseFlag == '1') {
                                return 1;
                              }
                              // 其他情况保持不变
                              return 0;
                            });
                          bankList.value.filter((item, index) => {
                            if (item.chooseFlag == '1') {
                              handleChangeCard(index, item)
                              console.log('选择成功！')
                            }
                          })
                        }
                        isShow.value = false
                        isShowPay.value = true
                      } else {
                        // 没有数据就显示输入银行卡号模块
                        router.push({
                          path: '/no_bindCard'
                        })
                      }
                    } else {
                      router.push({
                        path: '/fail'
                      })
                    }
                  }).catch((err) => {
                    router.push({
                      path: '/fail'
                    })
                  })
                }
              }
              if (res.data.status == 0) {
                setTimeout(() => {
                  ++numTime.value
                  if (numTime.value <= 10) {
                    getOtime()
                  } else {
                    proxy.$showToast("绑卡失败！")
                  }
                }, 1000);
              }

            }
            if (res.retCode == "00070000") {
              window.console.log(res.retMsg)
              if (!window.localStorage.getItem('isError')) {
                window.localStorage.setItem('isError', true)
                setTimeout(() => {
                  proxy.$showToast("绑卡失败！")
                }, 1000)
              }

              window.console.log(parsedParameters.value.mobileId)
              agreementAndBankInfo({
                mobileId: proxy.$globalFn.getStorage('phone') || parsedParameters.value.mobileId,
              }).then(res => {
                if (res.retCode == "0000") {
                  if (
                    res.data.bankAndAgreementInfoList &&
                    res.data.bankAndAgreementInfoList.length
                  ) {
                    // 查询的协议信息 有数据就跳转页面到 银行列表页
                    proxy.$globalFn.setStorage(
                      "userBankAndAgreementInfoList",
                      res.data.bankAndAgreementInfoList
                    );

                    bankList.value = proxy.$globalFn.getStorage('userBankAndAgreementInfoList') || []
                    // if (parsedParameters.value && parsedParameters.value.quick_sign_type && parsedParameters.value.quick_sign_type == 'quick-web') {
                    // }
                    isShow.value = false
                    isShowPay.value = true
                  } else {
                    bankList.value = []
                    isShow.value = false
                    isShowPay.value = true
                  }
                } else {
                  setTimeout(() => {
                    proxy.$showToast(res.retMsg)
                  }, 1000)
                }
              }).catch((err) => {
                router.push({
                  path: '/fail'
                })
              })

            }
          }).catch((err) => {
            proxy.$showToast(err)
          })
        }
        getOtime()

      } else {
        console.log(111)
        console.log(parsedParameters.value)
        // 首次进入 && 有手机号 && 有默认银行
        if (parsedParameters.value.mobileId && parsedParameters.value.gate_id) {

          agreementAndBankInfo({
            mobileId: parsedParameters.value.mobileId,
          }).then(res => {
            if (res.retCode == "0000") {
              if (
                res.data.bankAndAgreementInfoList &&
                res.data.bankAndAgreementInfoList.length
              ) {
                // 查询的协议信息 有数据就跳转页面到 银行列表页
                proxy.$globalFn.setStorage(
                  "userBankAndAgreementInfoList",
                  res.data.bankAndAgreementInfoList
                );

                bankList.value = proxy.$globalFn.getStorage('userBankAndAgreementInfoList') || []
                bankList.value.length > 1 && // 假设 bankList.value 是一个包含对象的数组
                  bankList.value.sort((a, b) => {
                    // 如果 a 的 chooseFlag 为 '1' 而 b 的 chooseFlag 不为 '1'，将 a 移动到前面
                    if (a.chooseFlag == '1' && b.chooseFlag != '1') {
                      return -1;
                    }
                    // 如果 a 的 chooseFlag 不为 '1' 而 b 的 chooseFlag 为 '1'，将 b 移动到前面
                    if (a.chooseFlag != '1' && b.chooseFlag == '1') {
                      return 1;
                    }
                    // 其他情况保持不变
                    return 0;
                  });
                bankList.value.filter((item, index) => {
                  if (item.chooseFlag == '1') {
                    handleChangeCard(index, item)
                    console.log('选择成功！')
                  }
                })
                isShow.value = false
                isShowPay.value = true
              } else {
                // 没有数据跳转三要素页面
                proxy.$globalFn.setStorage('identityCode', parsedParameters.value.identityCode || '')
                proxy.$globalFn.setStorage('cardHolder', parsedParameters.value.cardHolder || '')
                router.push({
                  path: '/no_bindCardForm',
                  query: {
                    gateId: parsedParameters.value.gate_id,
                    mediaId: parsedParameters.value.mobileId,
                  }
                })
              }
            } else {
              router.push({
                path: '/fail'
              })
            }
          }).catch((err) => {
            router.push({
              path: '/fail'
            })
          })

        }
      }
    }

  } else {
    console.log('22222')
    if (!proxy.$globalFn.getStorage('urlParameters')) {
      proxy.$showToast('解析url失败，请重试')
    } else {
      console.log('333333')
      parsedParameters.value = proxy.$globalFn.getStorage('urlParameters')
      handleGetLogo()
      getPaymentList();
    }
  }
}
const handleGetLogo = () => {
  if (process.env.NODE_ENV === 'development') {
    // 开发环境
    baseLogo.value = 'http://10.10.178.218:10010/cashier/checkout/image' + '?merId=' + parsedParameters.value.merId || '';
  } else {
    // 正式环境url
    baseLogo.value = 'https://pay.soopay.net/cashier/checkout/image' + '?merId=' + parsedParameters.value.merId || '';
  }
  // baseLogo.value = url
  getLogoImage({
    merId: parsedParameters.value.merId || ''
  }).then(res => {
    if (coverImgLogo.value) {
      isLogo.value = false
    } else {
      isLogo.value = true
    }

  }).catch((err) => {
    proxy.$showToast(err.retMsg);
  })
}

watch(isShowPay, (newVal, oldVal) => {
  if (!newVal) {
    activeTwo.value = null
  }
})

// 获取快捷初始化数据
function kuaigetPayInit() {
  let isPaySeq = proxy.$globalFn.getStorage('paySeq') || ''
  if (!isPaySeq) {
    userInfos.value.sourceSign = proxy.$globalFn.getStorage("urlSourceSign");
    quickPayment(userInfos.value).then(res => {
      if (res.retCode == "0000") {
        var isBankAndAgreementInfoList = res.data.bankAndAgreementInfoList; // 后台查询出的已签约的协议和卡信息 只要不为空 就是支付页

        var isBankInfo = res.data.bankInfo; // 商户传入的银行卡信息 如果 list为空 但是银行信息不为空 就签约
        var isMobileId = res.data.mobileId; //商户传入的手机号  如果list为空 但是手机号不为空 就添加新卡
        // 进行不同情况做页面显示处理
        if (isBankAndAgreementInfoList) {
          // 跳转到银行卡列表页
          proxy.$globalFn.setStorage("userBankAndAgreementInfoList", isBankAndAgreementInfoList);
          bankList.value = isBankAndAgreementInfoList || []
          // isShow.value = false
          isShowPay.value = true
          // handleRouterChange("/quickPaymentSelf", "");
          return;
        } else {
          if (isMobileId || isBankInfo) {

            // 判断是谁满足了
            if (isMobileId) {
              // 手机号有数据时
              // $(".payType").hide();
              bankList.value = []
              proxy.$globalFn.setStorage('phoneNumber', isMobileId)
              isShowPay.value = true
              enableBankList();
            } else {
              if (isBankInfo) {
                proxy.$globalFn.setStorage("isBankInfo", isBankInfo);
                // 银行卡信息有数据   跳转form表单签约页
                router.push({
                  path: '/bindCard',
                  // query: {
                  //   isBankInfo: JSON.stringify(isBankInfo)
                  // }
                })
                // handleRouterChange("/information", isBankInfo);
                return;
              } else {
                bankList.value = []
                isShowPay.value = true
              }
            }
          } else {
            // 两个信息都不满足
            // 手机号和银行卡信息都为空时 显示输入手机号的页面
            isShow.value = false
            isShowPay.value = false
          }
        }
      } else {

        proxy.$showToast(res.retMsg)
      }
    }).catch(err => {
      router.push({
        path: '/fail'
      })
    })
  }

}

// 获取微信的初始化数据
function weChatGetInit(type) {
  let param = {}
  param = proxy.$globalFn.getStorage('urlParameters')
  param.sourceSign = proxy.$globalFn.getStorage("urlSourceSign");
  param.payType = type

  weChatInit(param).then(res => {
    if (res.retCode == "0000") {
      isConfirmPayment.value = true
      window.location.href = res.data
    } else {
      proxy.$showToast(res.retMsg)
      return
    }
  }).catch(err => {
    proxy.$showToast(err)
    return
  })
}

const enableBankList = () => {
  var enMerId =
    proxy.$globalFn.getStorage("urlParameters") &&
    proxy.$globalFn.getStorage("urlParameters").merId;
  if (!enMerId) {
    proxy.$showToast("获取商户号失败");
    return;
  }

  enableBankListH5(
    { merId: enMerId }
  ).then(res => {
    if (res.retCode == "0000") {

      chuListData.value = res.data.creditList || [];
      depListData.value = res.data.debitList || [];
    } else {

      proxy.$showToast(res.retMsg);
    }
  }).catch((err) => {

    router.push({
      path: '/fail'
    })
  })
}
// 获取订单有效期时间
const getOrderTime = async () => {
  try {
    let res = await queryOrderExpireTime(userInfos.value)
    if (res.retCode == "0000") {
      effectTime.value = res.data;
      startCountDown(); // 开始倒计时
    } else {
      // 订单超时提示
      isTimeOut.value = true;
    }
  } catch (error) {
    console.error(error);
    proxy.$showToast("获取订单有效期时间接口错误，请重新尝试！")
  }
}
// 倒计时
function startCountDown() {
  var count = 0;
  // effectTime = effectTime;
  // }

  // var startTime = Date.now();
  if (orderTimer.value) {
    clearInterval(orderTimer.value);
    orderTimer.value = null;
  }
  orderTimer.value = setInterval(function () {
    count++;
    effectTime.value -= 1;
    proxy.$globalFn.setStorage('effectTime', effectTime.value)
    if (effectTime.value < 0) return;
    formatSeconds(effectTime.value);
    timeoutRemind(effectTime.value);
    if (effectTime.value <= 0 && orderTimer.value) {
      clearInterval(orderTimer.value);
      orderTimer.value = null;
    }
  }, 1000);
}
// 格式化时间
const formatSeconds = (seconds) => {

  if (seconds < 0) return;
  pay_minute.value = String((seconds / 60) | 0);
  pay_second.value = String(seconds % 60 | 0);
  if (pay_minute.value) {
    pay_minute.value = pay_minute.value < 10 ? "0" + pay_minute.value : pay_minute.value;
  }
  if (pay_second.value) {
    pay_second.value = pay_second.value < 10 ? "0" + pay_second.value : pay_second.value;
  }
}
// 超时提醒
function timeoutRemind(seconds) {
  if (seconds <= 0) {
    isTimeOut.value = true
    clearInterval(payInterval.value); // 倒计时结束后 清掉定时查询状态
    clearTimeout(queryStatus.value); // 倒计时结束后 清掉定时二维码失效时间
  }
}


const getImgPath = async (url) => {
  const imagePath = `@/assets/pay_${url}.png`;
  // const { default: imageUrl } = await import(imagePath);
  return imagePath;
}
const handleSubmitPay = (type) => {
  console.log('activeName', activeName.value)
  // 判断浏览器环境进行支付
  if (isWeChatBrowser.value) {
    // 微信环境
    if (activeName.value == 'weChat') {
      weChatGetInit(29)
      // window.location.href = 'https://wxaurl.cn/Wv1vBN6GUOe'
      return
    }
  } else if (isAliBrowser.value) {
    if (activeName.value == 'ali') {
      weChatGetInit(30)
      return
    }
  } else if (isNativeBrowser.value) {
    // 微信环境
    if (activeName.value == 'weChat') {
      weChatGetInit(29)
      // window.location.href = 'https://wxaurl.cn/Wv1vBN6GUOe'
      // window.location.href = 'weixin://dl/business/?t=your_miniapp_appid';
      return
    } else if (activeName.value == 'ali') {
      weChatGetInit(30)
      return
    } else if (activeName.value == 'unionpay') {
      // window.location.href = parsedParameters.value.网银
      // window.location.href = 'weixin://dl/business/?t=your_miniapp_appid';
      return
    }
  }


  switch (type) {
    case 1:
      if (proxy.$globalFn.getStorage('phoneNumber')) {
        isShowPay.value = true
        return
      }
      isShow.value = true
      break;
    case 2:
      if (activeTwo.value == null) {
        proxy.$showToast('请选择支付的银行卡')
        return
      }
      // isShowPay.value = true
      if (!userInfos.value.sourceSign) {
        userInfos.value.sourceSign = proxy.$globalFn.getStorage("urlSourceSign");
      }
      confirmH5(userInfos.value).then(res => {
        if (res.retCode == "0000") {

          setTimeout(function () {
            router.push({
              path: '/success',
              query: {
                payType: "kuaijie"
              }
            })
          }, 1000);
        } else {

          setTimeout(() => {
            router.push({
              path: '/error',
              query: {
                retMsg: encodeURIComponent(res.retMsg),
                payType: "kuaijie"
              }
            })
          }, 1000);
        }
        // 支付结果 * 0 支付成功 * 1 支付失败 * 2 支付中 * -1 冲正 * 5 不确定(请求支付网关超时，支付结果不明)
      }).catch(err => {

        router.push({
          path: '/fail'
        })
      })
      break;
  }


}
const handleTargetBank = () => {
  router.push({
    path: '/no_bindCard',
    // path: '/formBank',
  })
}
const handleCheckPayType = (payIndex, name) => {
  activeOne.value = payIndex
  activeName.value = name
  console.log('payIndex', payIndex, '----', name)
}
const handleClosePhone = () => {
  isShow.value = false
  isShowPay.value = false
  // proxy.$refs.phoneNumber.value = ''
  // isNextDisabled.value = true
}
const handlePhoneNext = () => {
  proxy.$globalFn.setStorage('phone', proxy.$refs.phoneNumber.value)
  let phoneParam = proxy.$refs.phoneNumber.value
  SetParamTmp({
    merId: parsedParameters.value.merId,
    // merId: '9995',
    orderId: parsedParameters.value.orderId,
    merDate: parsedParameters.value.orderDate,
    param: phoneParam,
  }).then(res => {
    window.console.log('存储成功', res)
  })
  agreementAndBankInfo({
    mobileId: proxy.$refs.phoneNumber.value
  }).then(res => {

    // res.data.bankAndAgreementInfoList = []
    if (res.retCode == "0000") {
      if (
        res.data.bankAndAgreementInfoList &&
        res.data.bankAndAgreementInfoList.length
      ) {
        // 查询的协议信息 有数据就跳转页面到 银行列表页
        proxy.$globalFn.setStorage(
          "userBankAndAgreementInfoList",
          res.data.bankAndAgreementInfoList
        );
        // bankList.value = list
        bankList.value = proxy.$globalFn.getStorage('userBankAndAgreementInfoList') || []
        if (parsedParameters.value && parsedParameters.value.quick_sign_type && parsedParameters.value.quick_sign_type == 'quick-web') {
          bankList.value.length > 1 && // 假设 bankList.value 是一个包含对象的数组
            bankList.value.sort((a, b) => {
              // 如果 a 的 chooseFlag 为 '1' 而 b 的 chooseFlag 不为 '1'，将 a 移动到前面
              if (a.chooseFlag == '1' && b.chooseFlag != '1') {
                return -1;
              }
              // 如果 a 的 chooseFlag 不为 '1' 而 b 的 chooseFlag 为 '1'，将 b 移动到前面
              if (a.chooseFlag != '1' && b.chooseFlag == '1') {
                return 1;
              }
              // 其他情况保持不变
              return 0;
            });
          bankList.value.filter((item, index) => {
            if (item.chooseFlag == '1') {
              handleChangeCard(index, item)
              console.log('选择成功！')
            }
          })
        }
        isShow.value = false
        isShowPay.value = true
      } else {
        // 没有数据就显示输入银行卡号模块
        router.push({
          path: '/no_bindCard'
        })
        // enableBankList();
      }
    } else {
      router.push({
        path: '/fail'
      })
    }
  }).catch((err) => {

    router.push({
      path: '/fail'
    })
  })
}
const handlePrev = () => {
  isShowPay.value = false
  isShow.value = true
  // if (proxy.$globalFn.getStorage('phoneNumber')) {
  //   proxy.$nextTick(() => {
  //     proxy.$refs.phoneNumber.value = proxy.$globalFn.getStorage('phoneNumber')
  //   })
  // }
}
const handleChangeCard = (index, item) => {
  activeTwo.value = index
  // userInfos.value.sourceSign = proxy.$globalFn.getStorage('urlSourceSign')
  userInfos.value.agreementId = item.agreementId
  userInfos.value.confirmBinBankId = item.binBankId
  userInfos.value.confirmBankCardType = item.bankAccType
}
const handleClearPhone = () => {
  proxy.$refs.phoneNumber.value = ''
  isClosePhone.value = false
  isNextDisabled.value = true
}
const handleTestPhone = proxy.$_.debounce((val) => {
  const msg = proxy.$globalFn.rules('phoneNumber', val)
  if (val == '') {
    isClosePhone.value = false
  } else {
    isClosePhone.value = true
  }
  // phoneNumber
  if (msg == true) {
    isNextDisabled.value = false
  } else {
    proxy.$showToast(msg);
    isNextDisabled.value = true
  }
}, 1000)
const handleGetPhoneAgree = () => {
  // proxy.$refs.phoneNumber.value

}
</script>

<style lang="sass" scoped>
@import '@/styles/variables.scss'
.page
  height: 100%
  background: #F8F8F8
  padding: 0px 14px
.top_image
  width: 120px
  height: 30px
  margin-top: 30px
  margin-bottom: 26px
  .logo_image
    width: 100%
    height: 100%
    object-fit: contain
.price_left
  font-size: 18px
  color: $global_color
  font-weight: 500
.price_right
  font-size: 25px
  color: $global_color
  font-weight: 500
.time_top
  margin-top: 12px
  margin-bottom: 16px
.top_three_left
  color: #666666
  font-size: 13px
  margin-right: 13px
.time_box
  // width: 22px
  // height: 22px
  padding: 3px 5px
  background: #EDEEEF
  color: $global_font_color
  font-size: 12px
  font-weight: bold
  border-radius: 4px
.dian
  color: $global_font_color
  font-size: 12px
  margin: 0px 3px
.line-container
  display: flex
  justify-content: center
  align-items: center
.line
  width: calc( 100% - 12px )
  height: 1px
  border: none
  outline: none
  // border-top: 1px dashed #D3D3D3
  // border-collapse: collapse
  // border-spacing: 100px
  background-image: linear-gradient(to right, #D3D3D3 50%, transparent 50%)
  background-size: 6px 1px
  margin-top: 10px
  margin-bottom: 20px
.content_text_box
  padding: 0px 12px
.text_flex
  color: #666666
  font-size: 13px
.payType_box
  border-radius: 10px
  padding: 18px 12px
  // padding-bottom: 18px
  padding-bottom: 0px
  background: #FFFFFF
  margin-top: 20px
  .title
    color: #222222
    font-size: 16px
    font-weight: bolder
    margin-bottom: 7px
.payType_first
  padding: 20px 0px
  border-bottom: 1px solid #E9E9E9
  position: relative
  .pay_img_box
    width: 20px
    height: 20px
  .pay_text
    color: $global_font_color
    font-size: 15px
    margin-left: 12px
  .dui_box
    width: 19px
    height: 19px
    align-self: flex-end
    position: absolute
    right: 0px
.payType_first:last-child
  border-bottom: none
.submit_pay
  width: calc( 100% - 40px )
  width: 100%
  position: fixed
  bottom: 0px
  background: #fff
  z-index: 666
  border-radius: 10px
  .flag_box
    display: flex
    align-items: center
    padding: 32px 20px 32px 20px
    // padding: 20px
    // padding-bottom: 0px
.nbsp
  height: 200px
  background: #F8F8F8
.action_sheet
  border-radius: 20px 20px 0px 0px

  .action_sheet_wrap
    padding: 24px
    padding-bottom: 80px
    .sheet_close
      color: #666666
      font-size: 15px
    .title
      color: $global_font_color
      font-weight: bold
      font-size: 17px
  .action_sheet_content
    padding-top: 35px
    padding-bottom: 15px
    display: flex
    align-items: center
    font-size: 15px
    border-bottom: 1px solid #E9E9E9
    margin-bottom: 22px
    position: relative
    .phone_title
      margin-right: 32px
    .phone_value
      border: none
      outline: none
    .phone_value::placeholder
      color: #CFCFCF
.title_left
  // margin-left: 97px
.bank_box
  padding: 17px 0 17px 0px
  border-bottom: 1px solid #E9E9E9
  position: relative
  .bank_box_icon_box
    display: flex
    align-items: center
    width: 24PX
    height: 24PX
    margin-right: 12px
  .bank_box_text
    color: $global_font_color
    font-size: 15px
  .bank_box_right_icon
    width: 19px
    height: 19px
    position: absolute
    right: 0px
.scroll_box
  max-height: 220px
  // overflow-y: scroll
.text_flex
  margin-bottom: 7px
#timeOut_box
  height: 300px !important
.alert_agreement
  text-align: center
  margin-bottom: 28px
:deep(.agreement_btn .van-button)
  color: #fff
  background: $global_color
:deep(.van-popup--center)
  z-index: 9999 !important
:deep(.van-popup)
  z-index: 9999 !important
.van-action-sheet__content
  padding-bottom:20px !important
.action_sheet_top
  margin-bottom: 19px
.Vector2x
  width: 16px
  height: 16px
  position: absolute
  right: 0
</style>
